package com.mirror.tk.web.controller.module.security;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.mirror.tk.core.log.annotation.Log;
import com.mirror.tk.core.module.sys.domain.SysRole;
import com.mirror.tk.core.module.sys.domain.SysUser;
import com.mirror.tk.core.module.sys.service.SysRoleService;
import com.mirror.tk.core.module.sys.service.SysUserService;
import com.mirror.tk.core.utils.RequestUtil;
import com.mirror.tk.framework.common.dao.support.PageInfo;
import com.mirror.tk.framework.common.exception.BusinessException;
import com.mirror.tk.framework.common.web.support.JsonListResult;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.security.support.Cryptos;
import com.mirror.tk.web.common.Constant;
import com.mirror.tk.web.common.support.SessionFace;
import com.mirror.tk.web.controller.CommonController;

@Controller
@RequestMapping(value = "/module/security/user")
public class SysUserController extends CommonController {

	@Resource
	private SysUserService sysUserService;

	@Resource
	private SysRoleService sysRoleService;
	
    //列表
    private static final String USER_LIST = "module/security/user/sys_user_list";
    //详情
    private static final String USER_VIEW = "module/security/user/sys_user_view";
    //添加、修改
    private static final String USER_DETAIL = "module/security/user/sys_user_detail";
    //重置密码（其他用户）
    private static final String USER_PASS = "module/security/user/sys_user_pass";
    //重置密码（自己）
    private static final String USER_CHANGE_PASS = "module/security/user/change_pass";

	int HASH_INTERATIONS = 1024;
	int SALT_SIZE = 8;

	// 列表
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(HttpServletRequest request, ModelMap map) {
		return USER_LIST;
	}
	
	// ajax列表
	@Log(action = "numbers", actionName = "获取数字队列", module = "DemoController", moduleName = "这是一个DEMO api文档")
	@ResponseBody
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public JsonListResult<SysUser> ajaxList(HttpServletRequest request,
			@RequestParam(value = "username", required = false) String username){
		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Boolean> sortMap = new HashMap<String, Boolean>();
		// 登录用户名
		if (StringUtils.isNotBlank(username)) {
			searchMap.put("LIKE_username", username);
		}
		PageInfo<SysUser> pageInfo = sysUserService.query(fromJsonListResult(request), searchMap, sortMap);
		return toJsonListResult(pageInfo);
	}

	// 增加-查看
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add(HttpServletRequest request, ModelMap map) {
		List<SysRole> roles = sysRoleService.getAll();
		map.put("roles", roles);
		return USER_DETAIL;
	}

	// 增加-保存
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public JsonResult postAdd(HttpServletRequest request, ModelMap map, SysUser sysUser) {
		JsonResult result = new JsonResult(false);
		try {
			if (sysUserService.checkUsername(sysUser.getUsername())) {
				// 已有同名记录存在
				result.setMessage(Constant.I18nMessage.CHECK_RECORD_EXISTS);
				result.setCode(Constant.Application.FAILURE);
				return result;
			}
			if (StringUtils.isNotBlank(sysUser.getPassword())) {
				entryptPassword(sysUser);
			} else {
				result.setMessage(Constant.I18nMessage.NEED_ENTER_PASSWORD);
				result.setCode(Constant.Application.FAILURE);
				return result;
			}
			// 用户所属角色
			sysUser.setRole(this.loadRoleFormRequest(request));
			// 主键ID
			sysUser.setId(null);
			// 创建时间
			sysUser.setCreateTime(new Date());
			// 最后登录时间
			sysUser.setLastLoginTime(new Date());
			// 最后登录IP
			sysUser.setLastLoginIp(RequestUtil.getRequestIpAddr(request));
			sysUser.setType(1);
			sysUserService.save(sysUser);
		} catch (Exception ex) {
			logger.error("Save Method (inster) SysUser Error : {}", sysUser.toString(), ex);
			// 增加失败
			result.setMessage(Constant.I18nMessage.SAVE_FAILURE);
			result.setCode(Constant.Application.FAILURE);
			return result;
		}
		// 操作提示
		result.setMessage(Constant.I18nMessage.SAVE_SUCCESS);
		result.setCode(Constant.Application.SUCCESS);
		result.setSuccess(true);
		return result;
	}

	// 修改-查看
	@RequestMapping(value = "update", method = RequestMethod.GET)
	public String update(HttpServletRequest request, ModelMap map, @RequestParam(value = "id") Long id) {
		SysUser sysUser = sysUserService.get(id);
		if (sysUser == null) {
			// 没有记录
			return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.RECORD_NOT_FOUND), map);
		}
		List<SysRole> roles = sysRoleService.getAll();
		map.put("item", sysUser);
		map.put("roles", roles);
		return USER_DETAIL;
	}

	// 修改-保存
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public JsonResult postUpdate(HttpServletRequest request, ModelMap map, SysUser sysUser) {
		JsonResult result = new JsonResult(false);
		if (sysUser == null || sysUser.getId() == null) {
			// 没有记录
			result.setMessage(Constant.I18nMessage.RECORD_NOT_FOUND);
			result.setCode(Constant.Application.FAILURE);
			return result;
		}
		try {
			SysUser sourceSysUser = sysUserService.get(sysUser.getId());
			if (sourceSysUser == null) {
				// 没有记录
				result.setMessage(Constant.I18nMessage.RECORD_NOT_FOUND);
				result.setCode(Constant.Application.FAILURE);
				return result;
			}
			// 用户所属角色
			sourceSysUser.setRole(this.loadRoleFormRequest(request));
			// 操作员姓名
			// sourceSysUser.setNickname(sysUser.getNickname());
			// 电子邮件
			sourceSysUser.setEmail(sysUser.getEmail());
			// 状态
			sourceSysUser.setStatus(sysUser.getStatus());
			// 描述
			sourceSysUser.setDescription(sysUser.getDescription());
			// 过期时间
			sourceSysUser.setExpiredTime(sysUser.getExpiredTime());
			// 解锁时间
			sourceSysUser.setUnlockTime(sysUser.getUnlockTime());
			sysUserService.update(sourceSysUser);
			sysUser = sourceSysUser;
		} catch (Exception ex) {
			logger.error("Save Method (Update) SysUser Error : {}", sysUser.toString(), ex);
			// 修改失败
			result.setMessage(Constant.I18nMessage.SAVE_FAILURE);
			result.setCode(Constant.Application.FAILURE);
			return result;
		}
		// 操作提示
		result.setMessage(Constant.I18nMessage.SAVE_SUCCESS);
		result.setCode(Constant.Application.SUCCESS);
		result.setSuccess(true);
		return result;
	}

	// 查看
	@RequestMapping(value = "view")
	public String show(HttpServletRequest request, ModelMap map, @RequestParam(value = "id") Long id) {
		SysUser sysUser = sysUserService.get(id);
		if (sysUser == null) {
			// 没有记录
			return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.RECORD_NOT_FOUND), map);
		}
		map.put("item", sysUser);
		return USER_VIEW;
	}

	// 修改状态
	@RequestMapping(value = "status")
	public JsonResult status(HttpServletRequest request,
			@RequestParam(value = "id", required = true) Long id,
			@RequestParam(value = "status", required = true) Integer status) {
		JsonResult result = new JsonResult(false);
		try {
			if (0 == sysUserService.updateStatusById(id, status)) {
				// 没有记录
				result.setMessage(Constant.I18nMessage.RECORD_NOT_FOUND);
				result.setCode(Constant.Application.FAILURE);
				return result;
			}
		} catch (Exception ex) {
			logger.error("status Method (status) SysUser Error : {}", id, ex);
			// 删除失败提示
			result.setMessage(Constant.I18nMessage.DEL_FAILURE);
			result.setCode(Constant.Application.FAILURE);
			return result;
		}
		// 操作提示
		result.setMessage(Constant.I18nMessage.DEL_SUCCESS);
		result.setCode(Constant.Application.SUCCESS);
		result.setSuccess(true);
		return result;
	}

	// 重置密码-查看
	@RequestMapping(value = "pass", method = RequestMethod.GET)
	public String resetPass(HttpServletRequest request,	ModelMap map, @RequestParam(value = "id", required = true) Long id) {
		SysUser sysUser = sysUserService.get(id);
		if (sysUser == null) {
			// 没有记录
			return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.RECORD_NOT_FOUND), map);
		}
		map.put("item", sysUser);
		return USER_PASS;
	}

	// 重置密码-修改
	@RequestMapping(value = "pass", method = RequestMethod.POST)
	public JsonResult resetPassSave(HttpServletRequest request, @RequestParam(value = "id", required = true) Long id) {
		JsonResult result = new JsonResult(false);
		String password = request.getParameter("newpassword");
		String password2 = request.getParameter("newpassword2");
		if (password == null || password2 == null || !password.equals(password2)) {
			result.setMessage(Constant.I18nMessage.USER_PASS_FORMAT_ERR);
			result.setCode(Constant.Application.FAILURE);
			return result;
		} else {
			SysUser sysUser = sysUserService.get(id);
			if (sysUser == null) {
				// 没有记录
				result.setMessage(Constant.I18nMessage.RECORD_NOT_FOUND);
				result.setCode(Constant.Application.FAILURE);
				return result;
			}
			sysUser.setPassword(password);
			entryptPassword(sysUser);
			sysUserService.save(sysUser);
			result.setMessage(Constant.I18nMessage.USER_PASS_UPDATE_SUCCESS);
			result.setCode(Constant.Application.SUCCESS);
			result.setSuccess(true);
			return result;
		}
	}

	// 修改密码-查看
	@RequestMapping(value = "changePass", method = RequestMethod.GET)
	public String changePass() {
		return USER_CHANGE_PASS;
	}

	// 修改密码-保存
	@RequestMapping(value = "changePass", method = RequestMethod.POST)
	public String changePassSave(HttpServletRequest request, ModelMap map) {
		String orginalPassword = request.getParameter("oldpassword");
		String password = request.getParameter("newpassword");
		String password2 = request.getParameter("newpassword2");
		if (StringUtils.isBlank(password) || StringUtils.isBlank(password2) || !password.equals(password2)) {
			return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.USER_PASS_FORMAT_ERR), map);
		} else {
			SysUser sysUser = sysUserService.get(SessionFace.getSessionUser(request).getId());
			if (sysUser == null) {
				// 没有记录
				return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.RECORD_NOT_FOUND), map);
			} else {
				boolean result = validatePassword(sysUser, orginalPassword);
				if (result) {
					sysUser.setPassword(password);
					entryptPassword(sysUser);
					sysUserService.save(sysUser);
					String location = "sys_user_list.html";
					return super.operSuccess(sysUser.getUsername() + " " + new RequestContext(request).getMessage(Constant.I18nMessage.USER_PASS_UPDATE_SUCCESS), location, map);
				} else {
					return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.USER_PASS_ORIGINAL_CHECK_ERR),	map);
				}
			}
		}
	}

	/**
	 * 
	 * 检查是否用户已经存在
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("check_name")
	@ResponseBody
	public JsonResult checkWaitress(HttpServletRequest request) {
		String username = request.getParameter("username");
		JsonResult result = new JsonResult();
		boolean status = sysUserService.checkUsername(username);
		if (status) {
			result.setMessage(Constant.I18nMessage.CHECK_RECORD_EXISTS);
			result.setCode("0");
			result.setSuccess(true);
		} else {
			result.setMessage(Constant.I18nMessage.SAVE_SUCCESS);
			result.setSuccess(false);
			result.setCode("-1");
		}
		return result;
	}

	private SysRole loadRoleFormRequest(HttpServletRequest request) {
		Long roleId = Long.valueOf(request.getParameter("roleId"));
		SysRole role = sysRoleService.get(roleId);
		return role;
	}

	/**
	 * 验证加密后的密码是否相同
	 * 
	 * @param user
	 * @param plaintPassword
	 * @return
	 * @throws BusinessException
	 */
	public boolean validatePassword(SysUser user, String plaintPassword) throws BusinessException {
		return entryptPassword(plaintPassword, user.getSalt()).equals(user.getPassword());
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 * 
	 * @param user
	 */
	private void entryptPassword(SysUser user) {
		user.setSalt(Cryptos.generatorSalt(SALT_SIZE));
		user.setPassword(Cryptos.sha1(user.getPassword(), user.getSalt(), HASH_INTERATIONS));
	}
	
	private String entryptPassword(String plainPassword, String salt) {
		return Cryptos.sha1(plainPassword, salt, HASH_INTERATIONS);
	}

}
